﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using static RuoVea.WeighIns.Server.Dto.DictDataInitializer;

namespace RuoVea.WeighIns.Server.Service;

/// <summary>
/// 体重记录服务
/// </summary>
[ApiExplorerSettings(GroupName = "WeighInfo")]
public partial class WeighInfoService : IApplicationService
{
    /// <summary>
    /// 体重记录仓储
    /// </summary>
    private readonly SugarRepository<InsWeighInfo> _thisRepository;
    /// <summary>
    /// 身体指标仓储
    /// </summary>
    private readonly SugarRepository<InsBodyMetrics> _bodyMetricsRepository;
    /// <summary>
    /// 时段字典仓储
    /// </summary>
    private readonly SugarRepository<InsMeridiem> _meridiemRepository;
    /// <summary>
    /// 当前用户
    /// </summary>
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="bodyMetricsRepository"></param>
    /// <param name="meridiemRepository"></param>
    /// <param name="currentUser"></param>
    public WeighInfoService(SugarRepository<InsWeighInfo> thisRepository, SugarRepository<InsBodyMetrics> bodyMetricsRepository, SugarRepository<InsMeridiem> meridiemRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _bodyMetricsRepository = bodyMetricsRepository;
        _meridiemRepository = meridiemRepository;
        _currentUser = currentUser;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="page"></param>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<InsWeighInfoDto>>> GetPagesAsync(WeighInfoPageParam page)
    {
        var restful = new RestfulResult<PageResult<InsWeighInfoDto>>() { Code = CodeStatus.OK };
        page ??= new WeighInfoPageParam { PageNo = 1, PageSize = 10 };

        // 先查询基础数据
        var baseQuery = await _thisRepository.AsQueryable()
            .Where(x => x.Creator == _currentUser.UserId)
            .WhereIF(page.Meridiem>0,x=>x.Meridiem==page.Meridiem)
            .WhereIF(page.WeighTime!=null,x=>x.WeighTime>=page.WeighTime)
            .OrderByDescending(x => x.WeighTime)
            .OrderByDescending(x => x.Meridiem)
            .Select(x => new InsWeighInfoDto
            {
                Id = x.Id,
                WeighTime = x.WeighTime,
                WeighKg = x.WeighKg,
                Meridiem = x.Meridiem,
                Sort = x.Sort,
                Remark = x.Remark,
                CreateTime = x.CreateTime,
                ModifyTime = x.ModifyTime,
                Creator = x.Creator,
                Modifier = x.Modifier,
                IsDelete = x.IsDelete
            })
            .ToPageAsync(page.PageNo, page.PageSize);

        // 再查询BodyMetrics数据并合并
        var ids = baseQuery.Rows.Select(x => x.Id).ToList();
        var bodyMetrics = await _bodyMetricsRepository.AsQueryable()
            .Where(x => ids.Contains(x.WeightRecordId))
            .ToListAsync();

        // 手动设置BodyMetrics数据
        foreach (var item in baseQuery.Rows)
        {
            var metrics = bodyMetrics.Where(x => x.WeightRecordId == item.Id).ToList();
            item.BodyFat = metrics.FirstOrDefault(t => t.MetricType == MetricTypes.BodyFat)?.MetricValue;
            item.MuscleMass = metrics.FirstOrDefault(t => t.MetricType == MetricTypes.MuscleMass)?.MetricValue;
            item.Water = metrics.FirstOrDefault(t => t.MetricType == MetricTypes.Water)?.MetricValue;
            item.BoneMass = metrics.FirstOrDefault(t => t.MetricType == MetricTypes.BoneMass)?.MetricValue;
            item.Bmr = metrics.FirstOrDefault(t => t.MetricType == MetricTypes.BMR)?.MetricValue;
            item.VisceralFat = metrics.FirstOrDefault(t => t.MetricType == MetricTypes.VisceralFat)?.MetricValue;
        }

        restful.Data = baseQuery;
        return restful;
    }

    /// <summary>
    /// 获取体重记录详情（包含扩展指标）
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<RestfulResult<InsWeighInfo>> GetDetailAsync(long id)
    {
        var restful = new RestfulResult<InsWeighInfo>();

        var record = await _thisRepository.GetFirstAsync(u => u.Id == id && u.Creator == _currentUser.UserId);

        if (record == null)
        {
            restful.Code = CodeStatus.NotFound;
            restful.Message = "记录不存在";
            return restful;
        }

        restful.Code = CodeStatus.OK;
        restful.Data = record;
        return restful;
    }

    /// <summary>
    /// 获取体重趋势数据
    /// </summary>
    /// <param name="days">查询天数</param>
    /// <returns></returns>
    public async Task<RestfulResult<List<WeightTrendPoint>>> GetWeightTrendAsync(int days = 30)
    {
        var restful = new RestfulResult<List<WeightTrendPoint>>();
        var startDate = DateTime.Now.AddDays(-days);

        var records = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId && u.WeighTime >= startDate)
            .Includes(u => u.MeridiemInfo) // 加载时段信息导航属性
            .Includes(u => u.BodyMetrics)   // 加载身体指标导航属性
            .OrderBy(u => u.WeighTime)
            .ToListAsync();

        var trendPoints = records.Select(r =>
        {
            var point = new WeightTrendPoint
            {
                Date = r.WeighTime,
                Weight = r.WeighKg,
                PeriodName = r.MeridiemInfo?.Name,
                Remark = r.Remark
            };

            // 获取体脂率（如有）
            var bodyFatMetric = r.BodyMetrics?.FirstOrDefault(b => b.MetricType == DictDataInitializer.MetricTypes.BodyFat);
            if (bodyFatMetric != null)
            {
                point.BodyFat = bodyFatMetric.MetricValue;
            }

            return point;
        }).ToList();

        restful.Code = CodeStatus.OK;
        restful.Data = trendPoints;
        return restful;
    }

    #region 获取体重统计数据
    /// <summary>
    /// 获取体重统计数据
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<WeightStatViewModel>> GetWeightStatAsync()
    {
        var restful = new RestfulResult<WeightStatViewModel>();

        var records = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .OrderByDescending(x => x.WeighTime)
            .ToListAsync();

        if (records.Count == 0)
        {
            restful.Code = CodeStatus.OK;
            restful.Data = new WeightStatViewModel();
            return restful;
        }

        var stat = new WeightStatViewModel
        {
            CurrentWeight = records.First().WeighKg,
            CurrentWeightTime = records.First().WeighTime,
            MaxWeight = records.Max(r => r.WeighKg),
            MinWeight = records.Min(r => r.WeighKg),
            TotalRecords = records.Count,
            RecordDays = records.GroupBy(r => r.WeighTime.Date).Count()
        };

        // 计算最高/最低体重时间
        stat.MaxWeightTime = records.FirstOrDefault(r => r.WeighKg == stat.MaxWeight)?.WeighTime;
        stat.MinWeightTime = records.FirstOrDefault(r => r.WeighKg == stat.MinWeight)?.WeighTime;

        // 计算相比上周变化量
        var lastWeekRecords = records.Where(r => r.WeighTime >= DateTime.Now.AddDays(-7)).ToList();
        if (lastWeekRecords.Count > 0)
        {
            var weekAgoRecords = records.Where(r => r.WeighTime >= DateTime.Now.AddDays(-14) && r.WeighTime < DateTime.Now.AddDays(-7)).ToList();
            if (weekAgoRecords.Count > 0)
            {
                stat.ChangeFromLastWeek = lastWeekRecords.Average(r => r.WeighKg) - weekAgoRecords.Average(r => r.WeighKg);
            }
        }

        // 计算相比上月变化量
        var lastMonthRecords = records.Where(r => r.WeighTime >= DateTime.Now.AddMonths(-1)).ToList();
        if (lastMonthRecords.Count > 0)
        {
            var monthAgoRecords = records.Where(r => r.WeighTime >= DateTime.Now.AddMonths(-2) && r.WeighTime < DateTime.Now.AddMonths(-1)).ToList();
            if (monthAgoRecords.Count > 0)
            {
                stat.ChangeFromLastMonth = lastMonthRecords.Average(r => r.WeighKg) - monthAgoRecords.Average(r => r.WeighKg);
            }
        }

        // 计算累计变化总量
        stat.TotalChange = records.First().WeighKg - records.Last().WeighKg;

        // 计算平均每周/每月变化率
        if (stat.RecordDays > 7)
        {
            var weeks = stat.RecordDays / 7.0;
            stat.AvgWeeklyChange = stat.TotalChange / weeks;
            stat.AvgMonthlyChange = stat.AvgWeeklyChange * 4.345;
        }

        restful.Code = CodeStatus.OK;
        restful.Data = stat;
        return restful;
    }
    #endregion

    #region 获取时段字典数据
    /// <summary>
    /// 获取时段字典数据
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<List<InsMeridiem>>> GetMeridiemListAsync()
    {
        var restful = new RestfulResult<List<InsMeridiem>>();

        var meridiemList = await _meridiemRepository.AsQueryable()
            .OrderBy(m => m.Sort)
            .ToListAsync();

        // 如果数据库中没有数据，初始化默认数据
        if (meridiemList.Count == 0)
        {
            var defaultMeridiems = DictDataInitializer.GetMeridiemData();
            await _meridiemRepository.InsertRangeAsync(defaultMeridiems);
            meridiemList = defaultMeridiems;
        }

        restful.Code = CodeStatus.OK;
        restful.Data = meridiemList;
        return restful;
    }
    #endregion

    #region 增加体重记录
    /// <summary>
    /// 增加体重记录
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    /// <summary>
    /// 增加体重记录
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> AddAsync([FromBody] InsWeighInfoDto data)
    {
        if (data == null)
            return Restful.Bad(CodeStatus.BadRequest, "体重数据不能为空");

        // 数据验证
        if (data.WeighKg <= 0)
            return Restful.Bad(CodeStatus.BadRequest, "体重必须大于0");

        if (data.Meridiem < 1 || data.Meridiem > 3)
            return Restful.Bad(CodeStatus.BadRequest, "时段值无效");

        // 检查是否已存在相同时间和时段的记录
        var isExist = await _thisRepository.IsAnyAsync(u =>
            u.WeighTime.Date == data.WeighTime.Date &&
            u.Meridiem == data.Meridiem &&
            u.Creator == _currentUser.UserId &&
            u.IsDelete == 0);

        if (isExist)
            return Restful.Bad(CodeStatus.BadRequest, "该时段的体重记录已存在");

        var result = await _thisRepository.Context.Ado.UseTranAsync(async () =>
        {
            // 设置创建信息
            data.Creator = _currentUser.UserId;
            data.CreateTime = DateTime.Now;
            data.ModifyTime = DateTime.Now;
            data.IsDelete = 0;

            // 插入主表记录（只插入InsWeighInfo基础字段）
            var mainRecord = data.Adapt<InsWeighInfo>();
            var ret = await _thisRepository.InsertReturnEntityAsync(mainRecord);

            if (ret != null && ret.Id > 0)
            {
                // 插入扩展指标到BodyMetrics表
                List<InsBodyMetrics> bodyMetricsList = new();

                // 体脂率
                if (data.BodyFat.HasValue && data.BodyFat.Value > 0)
                {
                    bodyMetricsList.Add(new InsBodyMetrics
                    {
                        Id = IdGenerator.Id,
                        WeightRecordId = ret.Id,
                        MetricType = MetricTypes.BodyFat,
                        MetricValue = data.BodyFat.Value,
                        MetricUnit = "%",
                        CreateTime = DateTime.Now
                    });
                }

                // 肌肉量
                if (data.MuscleMass.HasValue && data.MuscleMass.Value > 0)
                {
                    bodyMetricsList.Add(new InsBodyMetrics
                    {
                        Id = IdGenerator.Id,
                        WeightRecordId = ret.Id,
                        MetricType = MetricTypes.MuscleMass,
                        MetricValue = data.MuscleMass.Value,
                        MetricUnit = "kg",
                        CreateTime = DateTime.Now
                    });
                }

                // 水分率
                if (data.Water.HasValue && data.Water.Value > 0)
                {
                    bodyMetricsList.Add(new InsBodyMetrics
                    {
                        Id = IdGenerator.Id,
                        WeightRecordId = ret.Id,
                        MetricType = MetricTypes.Water,
                        MetricValue = data.Water.Value,
                        MetricUnit = "%",
                        CreateTime = DateTime.Now
                    });
                }

                // 骨量
                if (data.BoneMass.HasValue && data.BoneMass.Value > 0)
                {
                    bodyMetricsList.Add(new InsBodyMetrics
                    {
                        Id = IdGenerator.Id,
                        WeightRecordId = ret.Id,
                        MetricType = MetricTypes.BoneMass,
                        MetricValue = data.BoneMass.Value,
                        MetricUnit = "kg",
                        CreateTime = DateTime.Now
                    });
                }

                // 基础代谢
                if (data.Bmr.HasValue && data.Bmr.Value > 0)
                {
                    bodyMetricsList.Add(new InsBodyMetrics
                    {
                        Id = IdGenerator.Id,
                        WeightRecordId = ret.Id,
                        MetricType = MetricTypes.BMR,
                        MetricValue = data.Bmr.Value,
                        MetricUnit = "kcal",
                        CreateTime = DateTime.Now
                    });
                }

                // 内脏脂肪等级
                if (data.VisceralFat.HasValue && data.VisceralFat.Value > 0)
                {
                    bodyMetricsList.Add(new InsBodyMetrics
                    {
                        Id = IdGenerator.Id,
                        WeightRecordId = ret.Id,
                        MetricType = MetricTypes.VisceralFat,
                        MetricValue = data.VisceralFat.Value,
                        MetricUnit = "level",
                        CreateTime = DateTime.Now
                    });
                }

                if (bodyMetricsList.Count > 0)
                {
                    await _bodyMetricsRepository.InsertRangeAsync(bodyMetricsList);
                }
            }
            else
            {
                throw new Exception("体重记录插入失败");
            }
        });

        return result.Data == true
            ? Restful.Success(true)
            : Restful.Bad(CodeStatus.BadRequest, result.ErrorMessage ?? "添加失败");
    }
    #endregion

    #region 增加体重记录
    /// <summary>
    /// 更新体重记录
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> UpdateAsync([FromBody] InsWeighInfoDto data)
    {
        if (data == null)
            return Restful.Bad(CodeStatus.BadRequest, "体重数据不能为空");

        if (data.Id <= 0)
            return Restful.Bad(CodeStatus.BadRequest, "记录ID无效");

        // 检查记录是否存在且属于当前用户
        var existingRecord = await _thisRepository.GetFirstAsync(u =>
            u.Id == data.Id && u.Creator == _currentUser.UserId && u.IsDelete == 0);

        if (existingRecord == null)
            return Restful.Bad(CodeStatus.BadRequest, "记录不存在");

        // 检查时间和时段是否与其他记录冲突
        var conflictExist = await _thisRepository.IsAnyAsync(u =>
            u.Id != data.Id &&
            u.WeighTime.Date == data.WeighTime.Date &&
            u.Meridiem == data.Meridiem &&
            u.Creator == _currentUser.UserId &&
            u.IsDelete == 0);

        if (conflictExist)
            return Restful.Bad(CodeStatus.BadRequest, "该时段的体重记录已存在");

        // 数据验证
        if (data.WeighKg <= 0)
            return Restful.Bad(CodeStatus.BadRequest, "体重必须大于0");

        if (data.Meridiem < 1 || data.Meridiem > 3)
            return Restful.Bad(CodeStatus.BadRequest, "时段值无效");

        var result = await _thisRepository.Context.Ado.UseTranAsync(async () =>
        {
            // 更新主表记录
            var mainRecord = data.Adapt<InsWeighInfo>();
            mainRecord.Creator = existingRecord.Creator; // 保留原始创建者
            mainRecord.CreateTime = existingRecord.CreateTime; // 保留创建时间
            mainRecord.ModifyTime = DateTime.Now;
            mainRecord.Modifier = _currentUser.UserId;
            mainRecord.IsDelete = 0;

            var updateResult = await _thisRepository.UpdateAsync(mainRecord);
            if (!updateResult)
            {
                throw new Exception("体重记录更新失败");
            }

            // 更新扩展指标
            // 先删除原有的扩展指标
            var deleteResult = await _bodyMetricsRepository.DeleteAsync(b => b.WeightRecordId == data.Id);
            //if (!deleteResult)
            //{
            //    throw new Exception("删除原有身体指标失败");
            //}

            // 插入新的扩展指标
            List<InsBodyMetrics> bodyMetricsList = new();

            // 体脂率
            if (data.BodyFat.HasValue && data.BodyFat.Value > 0)
            {
                bodyMetricsList.Add(new InsBodyMetrics
                {
                    Id = IdGenerator.Id,
                    WeightRecordId = data.Id,
                    MetricType = MetricTypes.BodyFat,
                    MetricValue = data.BodyFat.Value,
                    MetricUnit = "%",
                    CreateTime = DateTime.Now
                });
            }

            // 肌肉量
            if (data.MuscleMass.HasValue && data.MuscleMass.Value > 0)
            {
                bodyMetricsList.Add(new InsBodyMetrics
                {
                    Id = IdGenerator.Id,
                    WeightRecordId = data.Id,
                    MetricType = MetricTypes.MuscleMass,
                    MetricValue = data.MuscleMass.Value,
                    MetricUnit = "kg",
                    CreateTime = DateTime.Now
                });
            }

            // 水分率
            if (data.Water.HasValue && data.Water.Value > 0)
            {
                bodyMetricsList.Add(new InsBodyMetrics
                {
                    Id = IdGenerator.Id,
                    WeightRecordId = data.Id,
                    MetricType = MetricTypes.Water,
                    MetricValue = data.Water.Value,
                    MetricUnit = "%",
                    CreateTime = DateTime.Now
                });
            }

            // 骨量
            if (data.BoneMass.HasValue && data.BoneMass.Value > 0)
            {
                bodyMetricsList.Add(new InsBodyMetrics
                {
                    Id = IdGenerator.Id,
                    WeightRecordId = data.Id,
                    MetricType = MetricTypes.BoneMass,
                    MetricValue = data.BoneMass.Value,
                    MetricUnit = "kg",
                    CreateTime = DateTime.Now
                });
            }

            // 基础代谢
            if (data.Bmr.HasValue && data.Bmr.Value > 0)
            {
                bodyMetricsList.Add(new InsBodyMetrics
                {
                    Id = IdGenerator.Id,
                    WeightRecordId = data.Id,
                    MetricType = MetricTypes.BMR,
                    MetricValue = data.Bmr.Value,
                    MetricUnit = "kcal",
                    CreateTime = DateTime.Now
                });
            }

            // 内脏脂肪等级
            if (data.VisceralFat.HasValue && data.VisceralFat.Value > 0)
            {
                bodyMetricsList.Add(new InsBodyMetrics
                {
                    Id = IdGenerator.Id,
                    WeightRecordId = data.Id,
                    MetricType = MetricTypes.VisceralFat,
                    MetricValue = data.VisceralFat.Value,
                    MetricUnit = "level",
                    CreateTime = DateTime.Now
                });
            }

            if (bodyMetricsList.Count > 0)
            {
                var insertResult = await _bodyMetricsRepository.InsertRangeAsync(bodyMetricsList);
                if (insertResult == false)
                {
                    throw new Exception("插入身体指标失败");
                }
            }
        });

        return result.Data == true
            ? Restful.Success(true)
            : Restful.Bad(CodeStatus.BadRequest, result.ErrorMessage ?? "修改失败");
    }
    #endregion

    #region 删除体重记录（物理删除）
    /// <summary>
    /// 删除体重记录（物理删除）
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        if (data == null)
            return Restful.Bad(CodeStatus.BadRequest, "删除数据不能为空");

        if (data.Id <= 0)
            return Restful.Bad(CodeStatus.BadRequest, "记录ID无效");

        // 检查记录是否存在且属于当前用户
        var existingRecord = await _thisRepository.GetFirstAsync(u =>
            u.Id == data.Id && u.Creator == _currentUser.UserId);

        if (existingRecord == null)
            return Restful.Bad(CodeStatus.BadRequest, "记录不存在");

        var result = await _thisRepository.Context.Ado.UseTranAsync(async () =>
        {
            // 删除扩展指标
            var metricsDeleteResult = await _bodyMetricsRepository.DeleteAsync(b => b.WeightRecordId == data.Id);
            //if (!metricsDeleteResult)
            //{
            //    throw new Exception("删除身体指标失败");
            //}

            // 删除主表记录
            var deleteResult = await _thisRepository.DeleteByIdAsync(data.Id);
            if (!deleteResult)
            {
                throw new Exception("删除体重记录失败");
            }
        });

        return result.Data == true
            ? Restful.Success(true)
            : Restful.Bad(CodeStatus.BadRequest, result.ErrorMessage ?? "删除失败");
    }
    #endregion

    #region 批量添加体重记录
    /// <summary>
    /// 批量添加体重记录
    /// </summary>
    /// <param name="records"></param>
    /// <returns></returns>
    public async Task<RestfulResult> BatchAddAsync([FromBody] List<InsWeighInfoDto> records)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (records == null || records.Count == 0)
        {
            restful.Message = "请提供有效的体重记录";
            return restful;
        }

        // 检查是否有重复的记录
        var userRecords = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .Select(u => new { u.WeighTime, u.Meridiem })
            .ToListAsync();

        var conflictRecords = records.Where(r =>
            userRecords.Any(ur => ur.WeighTime.Date == r.WeighTime.Date && ur.Meridiem == r.Meridiem)
        ).ToList();

        if (conflictRecords.Count > 0)
        {
            restful.Message = $"有{conflictRecords.Count}条记录与现有记录冲突";
            return restful;
        }

        int successCount = 0;
        var result = await _thisRepository.Context.Ado.UseTranAsync(async () =>
        {
            foreach (var record in records)
            {
                // 设置创建信息
                record.Creator = _currentUser.UserId;
                record.CreateTime = DateTime.Now;
                record.ModifyTime = DateTime.Now;
                record.IsDelete = 0;

                // 插入主表记录
                var mainRecord = record.Adapt<InsWeighInfo>();
                var ret = await _thisRepository.InsertReturnEntityAsync(mainRecord);

                if (ret != null && ret.Id > 0)
                {
                    successCount++;
                    
                    // 插入扩展指标到BodyMetrics表
                    List<InsBodyMetrics> bodyMetricsList = new();

                    // 体脂率
                    if (record.BodyFat.HasValue && record.BodyFat.Value > 0)
                    {
                        bodyMetricsList.Add(new InsBodyMetrics
                        {
                            Id = IdGenerator.Id,
                            WeightRecordId = ret.Id,
                            MetricType = MetricTypes.BodyFat,
                            MetricValue = record.BodyFat.Value,
                            MetricUnit = "%",
                            CreateTime = DateTime.Now
                        });
                    }

                    // 肌肉量
                    if (record.MuscleMass.HasValue && record.MuscleMass.Value > 0)
                    {
                        bodyMetricsList.Add(new InsBodyMetrics
                        {
                            Id = IdGenerator.Id,
                            WeightRecordId = ret.Id,
                            MetricType = MetricTypes.MuscleMass,
                            MetricValue = record.MuscleMass.Value,
                            MetricUnit = "kg",
                            CreateTime = DateTime.Now
                        });
                    }

                    // 水分率
                    if (record.Water.HasValue && record.Water.Value > 0)
                    {
                        bodyMetricsList.Add(new InsBodyMetrics
                        {
                            Id = IdGenerator.Id,
                            WeightRecordId = ret.Id,
                            MetricType = MetricTypes.Water,
                            MetricValue = record.Water.Value,
                            MetricUnit = "%",
                            CreateTime = DateTime.Now
                        });
                    }

                    // 骨量
                    if (record.BoneMass.HasValue && record.BoneMass.Value > 0)
                    {
                        bodyMetricsList.Add(new InsBodyMetrics
                        {
                            Id = IdGenerator.Id,
                            WeightRecordId = ret.Id,
                            MetricType = MetricTypes.BoneMass,
                            MetricValue = record.BoneMass.Value,
                            MetricUnit = "kg",
                            CreateTime = DateTime.Now
                        });
                    }

                    // 基础代谢
                    if (record.Bmr.HasValue && record.Bmr.Value > 0)
                    {
                        bodyMetricsList.Add(new InsBodyMetrics
                        {
                            Id = IdGenerator.Id,
                            WeightRecordId = ret.Id,
                            MetricType = MetricTypes.BMR,
                            MetricValue = record.Bmr.Value,
                            MetricUnit = "kcal",
                            CreateTime = DateTime.Now
                        });
                    }

                    // 内脏脂肪等级
                    if (record.VisceralFat.HasValue && record.VisceralFat.Value > 0)
                    {
                        bodyMetricsList.Add(new InsBodyMetrics
                        {
                            Id = IdGenerator.Id,
                            WeightRecordId = ret.Id,
                            MetricType = MetricTypes.VisceralFat,
                            MetricValue = record.VisceralFat.Value,
                            MetricUnit = "level",
                            CreateTime = DateTime.Now
                        });
                    }

                    if (bodyMetricsList.Count > 0)
                    {
                        await _bodyMetricsRepository.InsertRangeAsync(bodyMetricsList);
                    }
                }
            }
        });

        if (result.Data == true)
        {
            restful.Code = CodeStatus.OK;
            restful.Message = $"成功添加{successCount}条记录";
            restful.Data = new { count = successCount };
        }
        else
        {
            restful.Message = result.ErrorMessage ?? "批量添加失败";
        }
        
        return restful;
    }
    #endregion
}

